package com.gimi.cloud.jimi.merchantZone.consumer.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gimi.cloud.jimi.common.enums.ServiceNameConstants;
import com.gimi.cloud.jimi.common.mq.enume.QueueEnum;
import com.gimi.cloud.jimi.common.mq.service.MqCommonSenderService;
import com.gimi.cloud.jimi.common.utils.CommonUtil;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.dto.base.BaseDTO;
import com.gimi.cloud.jimi.dto.log.LogOperationDTO;
import com.gimi.cloud.jimi.merchantZone.consumer.service.store.StoreService;
import com.gimi.cloud.jimi.merchantZone.consumer.service.ueditor.UeditorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.enums.ServiceNameEnum;
import com.gimi.cloud.jimi.merchantZone.consumer.redis.IRedisService;
import com.gimi.cloud.jimi.merchantZone.consumer.service.product.ProductService;
import com.gimi.cloud.jimi.merchantZone.consumer.service.product.SkuService;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.common.utils.reqhead.Util;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;

/**
 * Created by luck on 2017/09/28.
 */
@CrossOrigin//允许跨域
@RestController
public class MerChantMicroServiceConsumerController {

	private static Logger logger = LoggerFactory.getLogger(MerChantMicroServiceConsumerController.class);
	private final IRedisService iRedisService;
	private final ProductService productService;
	private final StoreService storeService;
	private final SkuService skuService;
	private final UeditorService ueditorService;

	private final MqCommonSenderService mqCommonSenderService;

	@Autowired
	public MerChantMicroServiceConsumerController(IRedisService iRedisService, ProductService productService,
												  StoreService storeService,SkuService skuService,UeditorService ueditorService,
												  MqCommonSenderService mqCommonSenderService) {
		this.iRedisService = iRedisService;
		this.productService = productService;
		this.storeService = storeService;
		this.skuService = skuService;
		this.ueditorService = ueditorService;
		this.mqCommonSenderService = mqCommonSenderService;
	}

	/**
	 * 作为user服务的统一入口.
	 *
	 * @param requestData
	 *            请求参数
	 * @param request
	 *            httpRequest
	 * @param response
	 *            response
	 */
	@RequestMapping(value = "service")
	@ResponseBody
	public Response merchantZoneService(@RequestBody(required = false) String requestData, @RequestParam(value = "file",required = false) MultipartFile file,
									HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("===>进入商城微服务主程序入口.");
		logger.info("token===>" + request.getHeader("authorization"));
		logger.info("serviceName===>" + request.getHeader("serviceName"));

		/**
		 * 讲网关中的添加人更新人属性放入body
		 */
		String[] keys = new String[]{"serviceName","url","ip","authToken","uid","uname","addUid","addUname","addTime","updateUid","updateUname","updateTime"};
		requestData = CommonUtil.bodyHandle(requestData,request,keys);

		//记录日志
		LogOperationDTO logOperation = new LogOperationDTO();
		logOperation.setOpTime(new Date());

		Response resp = new Response();
		String serviceName=request.getHeader("serviceName");
		ServiceNameEnum serviceNameEnum = ServiceNameEnum.getStatus(serviceName);
		switch (serviceNameEnum) {
			case PRODUCT_LIST:
				resp = productService.productList(requestData, response, request);
				break;
			case ADD_PRODUCT:
                resp = productService.addProduct(requestData, response, request);
				break;
			case DELETE_PRODUCT:
				resp = productService.deleteProduct(requestData, response, request);
				break;
			case UP_SHELF_PRODUCT:
				resp = productService.upShelfProduct(requestData, response, request);
				break;
			case OFF_SHELF_PRODUCT:
				resp = productService.offShelfProduct(requestData, response, request);
				break;
			case GET_PRODUCT:
				resp = productService.getProduct(requestData, response, request);
				break;
			case UPDATE_PRODUCT:
				resp = productService.updateProduct(requestData, response, request);
				break;
			case GET_STORE_CATS:
				resp = productService.getStoreCats(requestData, response, request);
				break;
			case RELEASE_PRODUCT:
				resp = productService.releaseProduct(requestData, response, request);
				break;
			case MERCHANT_FILE_UPLOAD://商品文件上传
				resp = productService.fileUpload(requestData,file,response,request);
				break;


			case STORE_ADD://商铺添加
				resp = storeService.addStore(requestData, request, response);
				break;
			case STORE_UPDATE://商铺修改
				resp = storeService.updateStore(requestData, request, response);
				break;
			case STORE_LIST://商铺列表
				resp = storeService.storeList(requestData, request, response);
				break;
			case STORE_ALL_LIST://某商户所有店铺列表
				resp = storeService.allStoreList(requestData, request, response);
				break;
			case STORE_SINGLE://获取单个店铺
				resp = storeService.storeSingle(requestData, request, response);
				break;
			case STORE_AUTH://店铺审核
				resp = storeService.storeAuth(requestData, request, response);
				break;
			case STORE_DELETE://商铺删除
				resp = storeService.deleteStore(requestData, request, response);
				break;
			case STORE_UPLOAD://商品文件上传
				resp = storeService.fileUpload(response,request);
				break;
			case MERCHANT_STORE_ADD://商铺经营范围添加
				resp = storeService.addMerchantStore(requestData, request, response);
				break;
			case MERCHANT_STORE_ADD_LIST://商铺可添加经营范围列表
				resp = storeService.merchantStoreAddList(requestData, request, response);
				break;
			case MERCHANT_STORE_LIST://商铺经营范围列表
				resp = storeService.merchantStoreList(requestData, request, response);
				break;
			case MERCHANT_STORE_DELETE://商铺经营范围删除
				resp = storeService.deleteMerchantStore(requestData, request, response);
				break;

			case SKU_LIST://根据product_id获取Sku列表
				resp = skuService.listSku(requestData, request, response);
				break;
			case SKU_MODEL_DETAIL://sku模板属性关系转化
				resp = skuService.SkuModelDetail(requestData, request, response);
				break;
			case SKU_UPDATE://保存Sku列表
				resp = skuService.updateSku(requestData, request, response);
				break;
			case SKU_DELETE://删除一条Sku数据
				resp = skuService.deleteSku(requestData, request, response);
				break;
			case SKU_IMG://查看Sku图片
				resp = skuService.skuImg(requestData, request, response);
				break;
			case UEDITOR_ACTION:
				resp = ueditorService.ueditorAction(request, response);
			default:
				resp.setResponseCode(ResponseCodeEnum.SERVICE_NAME_NOT_FOUND);
				Util.sendResponse(JsonUtil.toJson(resp), response);
				break;
		}
		//登录路径和Ueditor操作路径不能打日志，因为没有初始化BaseDTO
		String[] notCheck = {ServiceNameConstants.MASTER_LOGIN, ServiceNameConstants.UEDITOR_ACTION};
		Boolean flag= Arrays.asList(notCheck).contains(serviceName);

		if(serviceNameEnum.isLog() && !flag ){
			BaseDTO baseDTO = JsonUtil.jsonToBean(requestData,BaseDTO.class);
			//请求服务名
			logOperation.setOpServiceName(serviceNameEnum.name() + "."+baseDTO.getServiceName());
			logOperation.setOpServiceDesc(serviceNameEnum.getDesc());
			logOperation.setMaId(baseDTO.getUid());
			logOperation.setMaName(baseDTO.getUname());
			logOperation.setOpModule("merchant");
			logOperation.setOpUrl(request.getRequestURI());
			logOperation.setOpIp(baseDTO.getIp());
			logOperation.setOpResptime(new Date());
			if(serviceNameEnum.isLogParam()){
				logOperation.setOpParams(requestData);
			}
			logOperation.setOpResponseCode(resp.getRes_code());
			if(serviceNameEnum.isLogResult()){
				logOperation.setOpResponse(JsonUtil.toJson(resp));
			}
			//推送数据到消息队列
			try{
				mqCommonSenderService.sendMessage2Rabbitmq(QueueEnum.OPERATION_LOG,logOperation);
			}catch(Exception e){
				logger.info("推送日志到消息队列失败");
				e.printStackTrace();
			}
		}

		logger.info("===>执行完毕.\n");
		return resp;
	}


}
